<template>
  <div class="purchase-order-add-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>新增盘点订单</h2>
      <div class="header-actions">
        <el-button @click="handleCancel">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
      </div>
    </div>

    <!-- 基础信息区域 -->
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>基础信息</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="purchase-form"
      >
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="盘点类型" prop="countType">
              <el-select v-model="formData.countType" placeholder="请选择">
                <el-option label="期初盘点" value="期初盘点" />
                <el-option label="存货盘点" value="存货盘点" />
                <el-option label="期末盘点" value="期末盘点" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="经办人" prop="handlerId">
              <el-select
                v-model="formData.handlerId"
                placeholder="请选择经办人"
                style="width: 100%"
              >
                <el-option
                  v-for="user in userList"
                  :key="user.user_Id"
                  :label="user.userTrueName || user.userName"
                  :value="user.user_Id"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="10">
            <el-form-item label="盘点开始日期" prop="startTime">
              <el-date-picker 
                v-model="formData.startTime" 
                type="datetime" 
                placeholder="请选择"
              />
            </el-form-item> 
          </el-col>

          <el-col :span="10"> 
            <el-form-item label="盘点结束日期" prop="endTime">
              <el-date-picker 
                v-model="formData.endTime" 
                type="datetime" 
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="仓库名称" prop="warehouseId" > 
              <el-select
                v-model="formData.warehouseId"
                placeholder="请选择仓库名称"
                style="width: 100%"
                @change="handleWarehouseChange"
              >
                <el-option
                  v-for="warehouse in warehouseList"
                  :key="warehouse.id"
                  :label="warehouse.name"
                  :value="warehouse.id"
                />
              </el-select>
              <el-button type="text" @click="handleWarehouseModel" >设置</el-button>
            </el-form-item>
          </el-col>
          
          <el-col :span="10"> 
            <el-form-item label="进货部门" prop="department">
              <el-select
                v-model="formData.department"
                placeholder="请选择进货部门"
                style="width: 100%"
              >
                <el-option
                  v-for="dept in deptList"
                  :key="dept.departmentId"
                  :label="dept.departmentName"
                  :value="dept.departmentName"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="formData.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入备注信息"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 盘点明细区域 -->
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>盘点明细</span>
          <!-- 添加货品按钮：仓库未选择时禁用并提示 -->
          <el-tooltip 
            v-if="!formData.warehouseId" 
            effect="dark" 
            content="请选择仓库!" 
            placement="top"
          >
            <el-button type="primary" disabled>
              <el-icon><Plus /></el-icon>
              添加货品
            </el-button>
          </el-tooltip>
          <el-button 
            v-else 
            type="primary" 
            @click="openProductDialog"
          >
            <el-icon><Plus /></el-icon>
            添加货品
          </el-button>
        </div>
      </template>

      <!-- 明细列表：完整列展示 -->
      <el-table :data="countItems" border style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column label="货品编号" prop="productCode" width="120" />
        <el-table-column label="货品名称" prop="productName" width="150" />
        <el-table-column label="规格型号" prop="spec" width="120" />
        <el-table-column label="单位" prop="unit" width="100">
          <template #default="{ row }">
            <el-select
              v-model="row.unit"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="unit in unitList"
                :key="unit.id"
                :label="unit.unitName"
                :value="unit.unitName"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="货品类型" prop="ProductType" width="120" />
        <el-table-column label="账面库存" prop="bookStock" width="100">
          <template #default="{ row, $index }">
            <el-input
              v-model.number="row.bookStock"
              placeholder="请输入"
              type="number"
              style="width: 100%"
              @input="calculateProfitLoss($index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="账面金额" prop="bookAmount" width="100">
          <template #default="{ row }">
            {{ row.bookAmount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="盘点库位" prop="countLocation" width="120">
          <template #default="{ row }">
            <el-select 
              v-model="row.countLocation" 
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option 
                v-for="loc in warehouseLocations" 
                :key="loc.id" 
                :label="loc.name" 
                :value="loc.name" 
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="盘点数量" prop="countQuantity" width="120">
          <template #default="{ row, $index }">
            <el-input
              v-model.number="row.countQuantity"
              placeholder="请输入"
              type="number"
              style="width: 100%"
              @input="calculateProfitLoss($index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="参考单价" prop="referencePrice" width="100">
          <template #default="{ row, $index }">
            <el-input
              v-model.number="row.referencePrice"
              placeholder="请输入"
              type="number"
              style="width: 100%"
              @input="calculateProfitLoss($index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="盈亏数量" prop="profitLossQuantity" width="100">
          <template #default="{ row }">
            <span :class="{ 'profit': row.profitLossQuantity > 0, 'loss': row.profitLossQuantity < 0 }">
              {{ row.profitLossQuantity }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="盘点状态" prop="countStatus" width="100">
          <template #default="{ row }">
            <!-- 根据数据库enum值显示详细状态 -->
            <el-tag v-if="row.profitLossQuantity > 0" type="success">盘盈</el-tag>
            <el-tag v-else-if="row.profitLossQuantity < 0" type="danger">盘亏</el-tag>
            <el-tag v-else type="info">无盈亏</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="盈亏金额" prop="profitLossAmount" width="100">
          <template #default="{ row }">
            <span :class="{ 'profit': row.profitLossAmount > 0, 'loss': row.profitLossAmount < 0 }">
              {{ row.profitLossAmount.toFixed(2) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" width="150">
          <template #default="{ row }">
            <el-input
              v-model="row.remark"
              placeholder="请输入备注"
              size="small">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ $index }">
            <el-button
              type="danger"
              size="small"
              @click="removeItem($index)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 合计信息：更新为需求的统计项 -->
      <div class="total-summary">
        <el-row justify="center">
          <el-col :span="24">
            <div class="summary-display">
              <span class="summary-item">账面库存: {{ totalbookStock.toFixed(2) }}</span>
              <span class="summary-item">账面金额: ¥{{ totalbookAmount.toFixed(2) }}</span>
              <span class="summary-item">盘点数量: {{ totalcountQuantity.toFixed(2) }}</span>
              <span class="summary-item">盘盈数量: {{ totalProfitQuantity.toFixed(2) }}</span>
              <span class="summary-item">盘亏数量: {{ totalLossQuantity.toFixed(2) }}</span>
              <span class="summary-item">盘盈金额: ¥{{ totalProfitAmount.toFixed(2) }}</span>
              <span class="summary-item">盘亏金额: ¥{{ totalLossAmount.toFixed(2) }}</span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button type="success" @click="handleSave" :loading="saveLoading">
        <el-icon><Check /></el-icon>
        保存盘点信息
      </el-button>
      <el-button @click="handleReset" size="large" style="margin-left: 20px;">
        <el-icon><Refresh /></el-icon>
        重置
      </el-button>
      <el-button @click="handleCancel" size="large" style="margin-left: 20px;">
        <el-icon><Close /></el-icon>
        取消
      </el-button>
    </div>
  </div>

  <!-- 货品选择对话框 -->
  <el-dialog
    v-model="productDialogVisible"
    title="选择货品"
    width="80%"
    :close-on-click-modal="false"
  >
    <div class="product-dialog">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-input
          v-model="productSearchKeyword"
          placeholder="搜索货品名称或编码"
          @input="searchProducts"
          style="width: 300px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 货品列表 -->
      <el-table
        :data="productList"
        border
        style="width: 100%"
        @selection-change="handleProductSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="goodsCode" label="货品编号" width="120" />
        <el-table-column prop="goodsName" label="货品名称" width="200" />
        <el-table-column prop="specModel" label="规格型号" width="150" />
        <el-table-column prop="purchasePrice" label="参考单价" width="100">
          <template #default="{ row }">
            ¥{{ row.purchasePrice }}
          </template>
        </el-table-column>
        <el-table-column prop="currentInventory" label="当前库存" width="100" />
        <el-table-column prop="typeName" label="货品类型" width="150" />
        <el-table-column prop="unitName" label="单位" width="150" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="productPagination.pageIndex"
          v-model:page-size="productPagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="productPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadProducts"
          @current-change="loadProducts"
        />
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="productDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmProductSelection">
          确定选择
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, 
  Plus, 
  Check, 
  Close, 
  Refresh, 
  Search 
} from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

// 获取实例
const { proxy } = getCurrentInstance()
const router = useRouter()

const deptList = ref([])
// 响应式数据
const formRef = ref()
const saveLoading = ref(false)
const productDialogVisible = ref(false)
const productSearchKeyword = ref('')

// 基础数据列表
const userList = ref([])
// 静态单位列表
const unitList = ref([
  { id: 'DWBH9708', unitName: '副' },
  { id: 'DWBH43456', unitName: '卷' },
  { id: 'DWBH2242', unitName: '只' },
  { id: 'DWBH1487', unitName: '部' },
  { id: 'DWBH8938', unitName: '支' },
  { id: 'DWBH7420', unitName: '包' },
  { id: 'DWBH795', unitName: '条' },
  { id: 'DWBH7087', unitName: '台' },
  { id: 'DWBH4611', unitName: '个' },
  { id: 'DWBH5456', unitName: '套' }
])
const productList = ref([])
// 静态仓库列表
const warehouseList = ref([])
// 仓库库位列表（静态示例，可根据实际仓库ID动态获取）
const warehouseLocations = ref([
  { id: 1, name: 'A区-01货架' },
  { id: 2, name: 'A区-02货架' },
  { id: 3, name: 'B区-01货架' },
  { id: 4, name: 'B区-02货架' },
  { id: 5, name: 'C区-01货架' },
])

// 货品分页
const productPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 选中的货品
const selectedProducts = ref([])

// 表单数据 - 使用小驼峰命名，与API要求一致
const formData = reactive({
  countCode: "",
  countType: "存货盘点",
  startTime: "",
  endTime: "",
  warehouseId: null,
  creatorId: 1,
  handlerId: null,
  department: "",
  createTime: new Date().toISOString(),
  countStatus: "",
  outStatus: "",
  inStatus: "",
  remark: ""
})

// 盘点明细 - 包含盈亏计算相关字段（保持大写开头）
const countItems = reactive([])

// 验证时间是否在23:00-次日1:00之间的函数
const validateNightTime = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请选择时间'))
  }
  const date = new Date(value)
  const hour = date.getHours()
  const minute = date.getMinutes()
  
  // 检查是否在23:00-次日1:00之间
  if ((hour === 23 && minute >= 0) || (hour === 0 && minute >= 0) || (hour === 1 && minute <= 0)) {
    callback()
  } else {
    callback(new Error('盘点时间必须在23:00-次日1:00之间'))
  }
}

// 验证开始和结束时间间隔是否在2小时之内的函数
const validateTimeInterval = (rule, value, callback) => {
  if (!value || !formData.startTime || !formData.endTime) {
    callback()
  } else {
    const startTime = new Date(formData.startTime)
    const endTime = new Date(formData.endTime)
    const timeDiff = (endTime - startTime) / (1000 * 60 * 60) // 转换为小时
    
    if (timeDiff <= 2) {
      callback()
    } else {
      callback(new Error('盘点开始和结束时间间隔不能超过2小时'))
    }
  }
}

// 验证开始时间小于结束时间的函数
const validateStartTimeBeforeEndTime = (rule, value, callback) => {
  if (!value || !formData.endTime) {
    callback()
  } else {
    if (new Date(value) < new Date(formData.endTime)) {
      callback()
    } else {
      callback(new Error('开始时间必须小于结束时间'))
    }
  }
}

// 验证结束时间大于开始时间的函数
const validateEndTimeAfterStartTime = (rule, value, callback) => {
  if (!value || !formData.startTime) {
    callback()
  } else {
    if (new Date(value) > new Date(formData.startTime)) {
      callback()
    } else {
      callback(new Error('结束时间必须大于开始时间'))
    }
  }
}

// 表单验证规则
const formRules = {
  countType: [{ required: true, message: '请选择盘点类型', trigger: 'change' }],
  handlerId: [{ required: true, message: '请选择经办人', trigger: 'change' }],
  startTime: [
    { required: true, message: '请选择盘点开始日期', trigger: 'change' },
    { validator: validateNightTime, trigger: 'change' },
    { validator: validateStartTimeBeforeEndTime, trigger: 'change' },
    { validator: validateTimeInterval, trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择盘点结束日期', trigger: 'change' },
    { validator: validateNightTime, trigger: 'change' },
    { validator: validateEndTimeAfterStartTime, trigger: 'change' },
    { validator: validateTimeInterval, trigger: 'change' }
  ],
  warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
  department: [{ required: true, message: '请选择进货部门', trigger: 'change' }] // 验证department字段
}

// 计算属性：合计统计
const totalbookStock = computed(() => {
  return countItems.reduce((sum, item) => sum + (parseFloat(item.bookStock) || 0), 0)
})

const totalbookAmount = computed(() => {
  return countItems.reduce((sum, item) => sum + (parseFloat(item.bookAmount) || 0), 0)
})

const totalcountQuantity = computed(() => {
  return countItems.reduce((sum, item) => sum + (parseFloat(item.countQuantity) || 0), 0)
})

// 盘盈数量（仅统计正数）
const totalProfitQuantity = computed(() => {
  return countItems.filter(item => item.profitLossQuantity > 0)
    .reduce((sum, item) => sum + parseFloat(item.profitLossQuantity || 0), 0)
})

// 盘亏数量（仅统计绝对值）
const totalLossQuantity = computed(() => {
  return countItems.filter(item => item.profitLossQuantity < 0)
    .reduce((sum, item) => sum + Math.abs(parseFloat(item.profitLossQuantity || 0)), 0)
})

// 盘盈金额（仅统计正数）
const totalProfitAmount = computed(() => {
  return countItems.filter(item => item.profitLossAmount > 0)
    .reduce((sum, item) => sum + parseFloat(item.profitLossAmount || 0), 0)
})

// 盘亏金额（仅统计绝对值）
const totalLossAmount = computed(() => {
  return countItems.filter(item => item.profitLossAmount < 0)
    .reduce((sum, item) => sum + Math.abs(parseFloat(item.profitLossAmount || 0)), 0)
})

// 计算盈亏数量、状态、金额
const calculateProfitLoss = (index) => {
  const item = countItems[index]
  if (!item) return

  // 1. 计算盈亏数量 = 盘点数量 - 账面库存
  item.profitLossQuantity = (parseFloat(item.countQuantity) || 0) - (parseFloat(item.bookStock) || 0)
  
  // 2. 计算盘点状态 - 严格按照数据库enum类型要求使用正确的值
  if (item.profitLossQuantity !== 0) {
    item.countStatus = '有盈亏' // 使用数据库允许的enum值
  } else {
    item.countStatus = '无盈亏' // 使用数据库允许的enum值
  }
  
  // 3. 计算盈亏金额 = 盈亏数量 × 参考单价
  item.profitLossAmount = item.profitLossQuantity * (parseFloat(item.referencePrice) || 0)
  
  // 4. 同步更新账面金额（原逻辑保留）
  item.bookAmount = (parseFloat(item.bookStock) || 0) * (parseFloat(item.referencePrice) || 0)
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    console.log('正在获取用户列表...')
    const response = await proxy.http.get('/api/InboundManagement/GetUserOptions', {}, false)
    if (response && response.success) {
      userList.value = response.data || []
    } else {
      ElMessage.error(response?.message || '获取用户列表失败')
      userList.value = []
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败，请检查网络连接')
    userList.value = []
  }
}

// 获取部门列表（恢复进货部门下拉框数据）
const fetchDeptList = async () => {
  try {
    console.log('正在获取部门列表...')
    const response = await proxy.http.get('/api/InboundManagement/GetdepartmentOptions', {}, false)
    if (response && response.success) {
      deptList.value = response.data || []
    } else {
      ElMessage.error(response?.message || '获取部门列表失败')
      deptList.value = []
    }
  } catch (error) {
    console.error('获取部门列表失败:', error)
    ElMessage.error('获取部门列表失败，请检查网络连接')
    deptList.value = []
  }
}

// 仓库切换时可触发的逻辑（如加载对应库位）
const handleWarehouseChange = (warehouseId) => {
  console.log('切换仓库:', warehouseId)
  // 实际项目中可根据仓库ID加载对应的库位列表
  // 示例：if (warehouseId === 1) warehouseLocations.value = [...]
}

// 获取货品列表
const loadProducts = async () => {
  try {
    const params = {
      keyword: productSearchKeyword.value,
      pageIndex: productPagination.pageIndex,
      pageSize: productPagination.pageSize
    }
    const response = await proxy.http.get('/api/InboundManagement/GetProductOptions', params, false)
    if (response && response.success) {
      productList.value = response.data || []
      productPagination.total = response.total || 0
    }
  } catch (error) {
    console.error('获取货品列表失败:', error)
    ElMessage.error('获取货品列表失败')
  }
}

// 搜索货品
const searchProducts = () => {
  productPagination.pageIndex = 1
  loadProducts()
}

// 打开货品选择对话框（已加仓库校验）
const openProductDialog = () => {
  productDialogVisible.value = true
  productSearchKeyword.value = ''
  selectedProducts.value = []
  loadProducts()
}

// 货品选择变化
const handleProductSelectionChange = (selection) => {
  selectedProducts.value = selection
}

// 确认选择货品
const confirmProductSelection = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择至少一个货品')
    return
  }
  if (!formData.warehouseId) {
    ElMessage.warning('请先选择仓库')
    productDialogVisible.value = false
    return
  }

  // 添加选中的货品到明细列表（包含货品类型）
  selectedProducts.value.forEach(product => {
    const exists = countItems.some(item => item.productId === product.id)
    if (!exists) {
      countItems.push({
        productId: product.id,
        productCode: product.goodsCode,
        productName: product.goodsName,
        spec: product.specModel || '',
        unit: product.unitName || '',
        ProductType: product.typeName || '', // 货品类型
        bookStock: product.currentInventory || 0,
        bookAmount: 0,
        countLocation: '',
        countQuantity: 0,
        referencePrice: product.purchasePrice || 0,
        profitLossQuantity: 0,
        profitLossAmount: 0,
        countStatus: '无盈亏', // 使用数据库默认值
        remark: ''
      })
      // 初始化计算
      calculateProfitLoss(countItems.length - 1)
    }
  })

  productDialogVisible.value = false
  ElMessage.success(`已添加 ${selectedProducts.value.length} 个货品`)
}

// 删除明细项
const removeItem = (index) => {
  ElMessageBox.confirm('确定要删除这个货品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    countItems.splice(index, 1)
    ElMessage.success('删除成功')
  })
}

// 保存盘点单
const handleSave = async () => {
  try {
    saveLoading.value = true
    
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) {
      saveLoading.value = false
      return
    }
    
    // 确保 formData 存在，如果不存在则从 formRef 中获取
    const formDataInstance = formData || formRef.value?.model || {};
  
    // 验证是否有盘点明细
    if (!Array.isArray(countItems) || countItems.length === 0) {
      ElMessage.error('请至少添加一条盘点明细')
      saveLoading.value = false
      return
    }
  
    // 验证所有明细项
    for (const item of countItems) {
      if (!item.productCode || !item.productName || !item.bookStock || !item.countQuantity) {
        ElMessage.error('请完善所有明细项的必填信息')
        saveLoading.value = false
        return
      }
      // 验证数字字段
      if (isNaN(parseFloat(item.bookStock)) || isNaN(parseFloat(item.countQuantity))) {
        ElMessage.error('盘点数量和账面库存必须为数字')
        saveLoading.value = false
        return
      }
    }
    
    // 处理表单字段长度
    if (formDataInstance.countCode && formDataInstance.countCode.length > 50) {
      ElMessage.error('盘点单号长度不能超过50个字符')
      saveLoading.value = false
      return
    }
    
    // 准备临时盘点单号，为空时由后端生成
    const tempCountCode = formDataInstance.countCode || ''
    
    // 确保有有效的经办人ID
    if (!formDataInstance.handlerId || isNaN(formDataInstance.handlerId)) {
      ElMessage.error('请选择有效的经办人')
      saveLoading.value = false
      return
    }
    
    // 确保有有效的仓库ID
    if (!formDataInstance.warehouseId || isNaN(formDataInstance.warehouseId)) {
      ElMessage.error('请选择有效的仓库')
      saveLoading.value = false
      return
    }
    
    // 确保必填字段存在且有效
    if (!formDataInstance.startTime) {
      ElMessage.error('请选择开始时间')
      saveLoading.value = false
      return
    }
    
    if (!formDataInstance.endTime) {
      ElMessage.error('请选择结束时间')
      saveLoading.value = false
      return
    }
    
    if (!formDataInstance.department || formDataInstance.department.trim() === '') {
      ElMessage.error('请输入部门信息')
      saveLoading.value = false
      return
    }
    
    // 确保开始时间不晚于结束时间
    if (new Date(formDataInstance.startTime) > new Date(formDataInstance.endTime)) {
      ElMessage.error('开始时间不能晚于结束时间')
      saveLoading.value = false
      return
    }
    
    // 基础数据验证 - 确保countItems存在且为数组
    if (!Array.isArray(countItems) || countItems.length === 0) {
      ElMessage.error('请至少添加一条盘点明细');
      saveLoading.value = false;
      return;
    }
    
    // 创建基础数据对象
    const baseData = {
      // 严格使用小驼峰命名规范，符合ASP.NET Core Web API要求
      inventoryCount: {
        countCode: String(tempCountCode || ''),
        countType: String(formDataInstance.countType || '存货盘点'),
        warehouseId: parseInt(formDataInstance.warehouseId) || 0,
        handlerId: parseInt(formDataInstance.handlerId) || 0,
        creatorId: parseInt(formDataInstance.creatorId || 1) || 1,
        department: String(formDataInstance.department || '默认部门'),
        startTime: formDataInstance.startTime ? new Date(formDataInstance.startTime).toISOString() : new Date().toISOString(),
        endTime: formDataInstance.endTime ? new Date(formDataInstance.endTime).toISOString() : new Date().toISOString(),
        createTime: new Date().toISOString(),
        lastUpdateTime: new Date().toISOString(),
        totalAmount: 0,
        totalQuantity: 0,
        varianceTotal: 0,
        varianceAmount: 0,
        status: '新建',
        auditStatus: '待审核',
        isDeleted: false,
        tenantId: 1,
        checkerId: 0,
        checkTime: null,
        remark: String(formDataInstance.remark || ''),
        dataSource: 'Web',
        lastUpdateUserId: parseInt(formDataInstance.creatorId || 1) || 1,
        countName: String(formDataInstance.countName || '盘点'),
        checkerName: '',
        creatorName: '系统管理员',
        handlerName: String(formDataInstance.handlerName || '管理员')
      },
      countItems: countItems.map((item, index) => {
        const safeItem = item || {};
        const bookStock = parseFloat(safeItem.bookStock || 0);
        const countQuantity = parseFloat(safeItem.countQuantity || 0);
        const unitPrice = parseFloat(safeItem.unitPrice || 0);
        const bookAmount = parseFloat(safeItem.bookAmount || bookStock * unitPrice);
        
        return {
          countCode: String(tempCountCode || ''),
          productId: parseInt(safeItem.productId || 0) || 0,
          productCode: String(safeItem.productCode || `PROD${String(index + 1).padStart(3, '0')}`),
          productName: String(safeItem.productName || `产品${index + 1}`),
          spec: String(safeItem.spec || ''),
          unit: String(safeItem.unit || '个'),
          bookStock: bookStock,
          bookAmount: bookAmount,
          countLocation: String(safeItem.countLocation || ''),
          countQuantity: countQuantity,
          varianceQuantity: countQuantity - bookStock,
          varianceAmount: countQuantity * unitPrice - bookAmount,
          unitPrice: unitPrice,
          taxRate: parseFloat(safeItem.taxRate || 0),
          taxAmount: 0,
          lineNum: index + 1,
          batchNo: String(safeItem.batchNo || ''),
          expiryDate: safeItem.expiryDate ? new Date(safeItem.expiryDate).toISOString() : null,
          serialNo: String(safeItem.serialNo || ''),
          isDeleted: false,
          createTime: new Date().toISOString(),
          lastUpdateTime: new Date().toISOString(),
          tenantId: 1
        };
      })
    };
    
    // 根据API规范构建完整的数据结构
    const currentDate = new Date().toISOString();
    const submitData = {
      // 完整的inventoryCount对象，按照API规范提供所有必需字段
      inventoryCount: {
        // 核心必填字段 - 确保类型安全
        countCode: String(tempCountCode || ''),
        countType: String(formDataInstance.countType || '期初盘点'),
        warehouseId: parseInt(formDataInstance.warehouseId) || 0,
        handlerId: parseInt(formDataInstance.handlerId) || 0,
        creatorId: parseInt(formDataInstance.creatorId || 1) || 1,
        department: String(formDataInstance.department || '盘点员'),
        
        // 必需的时间字段
        startTime: formDataInstance.startTime ? new Date(formDataInstance.startTime).toISOString() : currentDate,
        endTime: formDataInstance.endTime ? new Date(formDataInstance.endTime).toISOString() : currentDate,
        createTime: currentDate,
        // 按照请求体要求设置null值
        countStatus: null,
        outStatus: null,
        inStatus: null,
        remark: formDataInstance.remark || ''
      },
      
      // 完整的countItems数组，按照API规范提供所有必需字段，移除countStatus字段
      countItems: Array.isArray(countItems) ? countItems
        .filter(item => item && item.productCode && item.productName) // 过滤条件
        .map((item, index) => {
          const safeItem = item || {};
          const bookStock = parseFloat(safeItem.bookStock || 0);
          const countQuantity = parseFloat(safeItem.countQuantity || 0);
          const unitPrice = parseFloat(safeItem.referencePrice || safeItem.unitPrice || 0);
          const bookAmount = bookStock * unitPrice; // 计算账面库存金额
          const profitLossQuantity = countQuantity - bookStock;
          const profitLossAmount = profitLossQuantity * unitPrice;
          
          // 返回完整对象，按照API规范提供所有必需字段
          return {
            countCode: String(tempCountCode || ''),
            productId: parseInt(safeItem.productId) || 0,
            productCode: String(safeItem.productCode || `PROD${String(index + 1).padStart(3, '0')}`),
            productName: String(safeItem.productName || `产品${index + 1}`),
            spec: String(safeItem.spec || ''),
            unit: String(safeItem.unit || '个'),
            bookStock: bookStock,
            bookAmount: bookAmount,
            countLocation: String(safeItem.countLocation || ''),
            countQuantity: countQuantity,
            profitLossQuantity: profitLossQuantity,
            profitLossAmount: profitLossAmount,
            referencePrice: unitPrice,
            inOutStatus: null,
            remark: safeItem.remark || ''
          };
        })
        : []
    };
    
    // 重要：打印完整的提交数据结构，以便用户复制到Swagger中测试
    console.log('\n===== 完整提交数据结构（可复制到Swagger） =====');
    
    // 生成动态的JSON示例，基于当前表单和明细数据，移除countStatus字段
    const dynamicExample = {
      "inventoryCount": {
        "countCode": formData.countCode || "",
        "countType": formData.countType || "期初盘点",
        "startTime": formData.startTime ? new Date(formData.startTime).toISOString() : new Date().toISOString(),
        "endTime": formData.endTime ? new Date(formData.endTime).toISOString() : new Date().toISOString(),
        "warehouseId": formData.warehouseId || 0,
        "creatorId": formData.creatorId || 0,
        "handlerId": formData.handlerId || 0,
        "department": formData.department || "",
        "createTime": new Date().toISOString(),
        "countStatus": null,
        "outStatus": null,
        "inStatus": null,
        "remark": formData.remark || ""
      },
      "countItems": Array.isArray(countItems) && countItems.length > 0 ? countItems.slice(0, 1).map(item => ({
        "countCode": formData.countCode || "",
        "productId": item.productId || 0,
        "productCode": item.productCode || "",
        "productName": item.productName || "",
        "spec": item.spec || "",
        "unit": item.unit || "",
        "bookStock": item.bookStock || 0,
        "bookAmount": item.bookAmount || 0,
        "countLocation": item.countLocation || "",
        "countQuantity": item.countQuantity || 0,
        "profitLossQuantity": item.profitLossQuantity || 0,
        "profitLossAmount": item.profitLossAmount || 0,
        "referencePrice": item.referencePrice || 0,
        "inOutStatus": null,
        "remark": item.remark || ""
      })) : [{
        // 如果没有数据，显示示例数据
        "countCode": "",
        "productId": 4,
        "productCode": "SP0012",
        "productName": "香辣味薯片",
        "spec": "135g/袋",
        "unit": "套",
        "bookStock": 796,
        "bookAmount": 3343.2000000000003,
        "countLocation": "A区-01货架",
        "countQuantity": 780,
        "profitLossQuantity": -16,
        "profitLossAmount": -67.2,
        "referencePrice": 4.2,
        "inOutStatus": null,
        "remark": "测试"
      }]
    };
    console.log(JSON.stringify(dynamicExample, null, 2));
    console.log('\n请复制以上JSON数据到Swagger中测试！');
    
    // 关键验证：确保数组不为空
    if (!submitData.countItems || submitData.countItems.length === 0) {
      ElMessage.error('请至少添加一条有效的盘点明细');
      saveLoading.value = false;
      return;
    }
    
    // 超级详细日志，帮助诊断问题 - 我们需要了解完整的数据结构
    console.log('===== 提交数据诊断报告 =====');
    console.log('1. 整体数据结构:');
    console.log('inventoryCount存在:', !!submitData.inventoryCount);
    console.log('countItems存在且为数组:', Array.isArray(submitData.countItems));
    console.log('countItems长度:', submitData.countItems.length);
    
    console.log('\n2. inventoryCount关键字段验证:');
    console.log('countCode:', submitData.inventoryCount.countCode, '类型:', typeof submitData.inventoryCount.countCode);
    console.log('warehouseId:', submitData.inventoryCount.warehouseId, '类型:', typeof submitData.inventoryCount.warehouseId);
    console.log('handlerId:', submitData.inventoryCount.handlerId, '类型:', typeof submitData.inventoryCount.handlerId);
    console.log('creatorId:', submitData.inventoryCount.creatorId, '类型:', typeof submitData.inventoryCount.creatorId);
    console.log('department:', submitData.inventoryCount.department, '类型:', typeof submitData.inventoryCount.department);
    console.log('startTime:', submitData.inventoryCount.startTime, '类型:', typeof submitData.inventoryCount.startTime);
    console.log('endTime:', submitData.inventoryCount.endTime, '类型:', typeof submitData.inventoryCount.endTime);
    
    console.log('\n3. countItems首项数据验证:');
    if (submitData.countItems.length > 0) {
      const firstItem = submitData.countItems[0];
      console.log('productId:', firstItem.productId, '类型:', typeof firstItem.productId);
      console.log('productCode:', firstItem.productCode, '类型:', typeof firstItem.productCode);
      console.log('productName:', firstItem.productName, '类型:', typeof firstItem.productName);
      console.log('bookStock:', firstItem.bookStock, '类型:', typeof firstItem.bookStock);
      console.log('countQuantity:', firstItem.countQuantity, '类型:', typeof firstItem.countQuantity);
      console.log('unitPrice:', firstItem.unitPrice, '类型:', typeof firstItem.unitPrice);
      console.log('lineNum:', firstItem.lineNum, '类型:', typeof firstItem.lineNum);
      console.log('isDeleted:', firstItem.isDeleted, '类型:', typeof firstItem.isDeleted);
      console.log('tenantId:', firstItem.tenantId, '类型:', typeof firstItem.tenantId);
    }
    
    // 序列化测试 - 确保所有数据都能正确序列化
    try {
      const serializedData = JSON.stringify(submitData);
      console.log('\n4. JSON序列化测试: 成功');
      console.log('序列化后数据大小:', serializedData.length, '字符');
    } catch (serializationError) {
      console.error('\n4. JSON序列化错误:', serializationError.message);
    }
    
    // 尝试使用另一种方式构建数据结构，可能后端需要不同的格式
    console.log('\n5. 准备发送API请求...');
    
    // 严格按照API规范构建完整的数据结构，使用小驼峰命名
    const simplifiedData = {
      // 完整的inventoryCount对象，包含API规范中的所有字段
      inventoryCount: {
        countCode: formDataInstance.countCode,
        countType: formDataInstance.countType || 'Regular',
        startTime: formDataInstance.startTime || currentDate,
        endTime: formDataInstance.endTime || currentDate,
        warehouseId: formDataInstance.warehouseId || 0,
        creatorId: formDataInstance.creatorId || 0,
        handlerId: formDataInstance.handlerId || 0,
        department: formDataInstance.department || '',
        createTime: currentDate,
        countStatus: null, // 按照请求体要求设置null值
        outStatus: null, // 按照请求体要求设置null值
        inStatus: null, // 按照请求体要求设置null值
        remark: formDataInstance.remark || ''
      },
      // 完整的countItems数组，包含API规范中的所有字段
      countItems: Array.isArray(countItems) ? countItems
        .filter(item => item && item.productCode && item.productName)
        .map(item => ({
          countCode: formDataInstance.countCode || '',
          productId: item.productId || 0,
          productCode: item.productCode || '',
          productName: item.productName || '',
          spec: item.spec || '',
          unit: item.unit || '',
          bookStock: parseFloat(item.bookStock || 0),
          bookAmount: parseFloat(item.bookAmount || 0),
          countLocation: item.countLocation || '',
          countQuantity: parseFloat(item.countQuantity || 0),
          profitLossQuantity: parseFloat(item.countQuantity || 0) - parseFloat(item.bookStock || 0),
          profitLossAmount: (parseFloat(item.countQuantity || 0) - parseFloat(item.bookStock || 0)) * parseFloat(item.referencePrice || 0),
          referencePrice: parseFloat(item.referencePrice || 0),
          inOutStatus: parseFloat(item.countQuantity || 0) - parseFloat(item.bookStock || 0) > 0 ? '盘盈' : parseFloat(item.countQuantity || 0) - parseFloat(item.bookStock || 0) < 0 ? '盘亏' : '持平',
          remark: item.remark || ''
        })) : []
    };
    
    console.log('\n6. 简化数据结构验证:');
    console.log('简化后的inventoryCount:', simplifiedData.inventoryCount);
    console.log('简化后的countItems长度:', simplifiedData.countItems.length);
    
    // 发送请求 - 使用符合API规范的数据结构
    console.log('【API请求准备】');
    console.log('URL:', '/api/InventoryCount/SaveInventoryCount');
    console.log('提交数据大小:', JSON.stringify(simplifiedData).length, '字符');
    console.log('inventoryCount字段数量:', Object.keys(simplifiedData.inventoryCount).length);
    console.log('countItems项数:', simplifiedData.countItems.length);
    
    // 再次打印完整的数据结构用于调试
    console.log('\n最终提交数据详情:');
    console.log('inventoryCount:', simplifiedData.inventoryCount);
    if (simplifiedData.countItems.length > 0) {
      console.log('countItems[0]:', simplifiedData.countItems[0]);
    }
    
    let response;
    try {
      console.log('开始发送API请求...');
      // 使用符合API规范的数据结构提交
      response = await proxy.http.post('/api/InventoryCount/SaveInventoryCount', simplifiedData, false);
      console.log('API响应成功:', response);
    } catch (error) {
      console.error('API请求失败:', error);
      
      // 超级详细的错误日志
      console.group('详细错误信息:');
      console.error('错误类型:', error.name || typeof error);
      console.error('错误消息:', error.message);
      console.error('错误堆栈:', error.stack);
      
      // 重要：将完整的请求数据保存到控制台，以便复制到Swagger
      console.error('\n===== 请求数据（可复制到Swagger） =====');
      console.error(JSON.stringify(simplifiedData, null, 2));
      
      // 打印完整的提交数据结构示例
      console.log('\n===== 完整提交数据结构（可复制到Swagger） =====');
      console.log(JSON.stringify({
        "inventoryCount": {
          "countCode": "string",
          "countType": "string",
          "startTime": "2025-10-30T01:13:21.386Z",
          "endTime": "2025-10-30T01:13:21.386Z",
          "warehouseId": 0,
          "creatorId": 0,
          "handlerId": 0,
          "department": "string",
          "createTime": "2025-10-30T01:13:21.386Z",
          "countStatus": "string",
          "outStatus": "string",
          "inStatus": "string",
          "remark": "string"
        },
        "countItems": [
          {
            "countCode": "string",
            "productId": 0,
            "productCode": "string",
            "productName": "string",
            "spec": "string",
            "unit": "string",
            "bookStock": 0,
            "bookAmount": 0,
            "countLocation": "string",
            "countQuantity": 0,
            "profitLossQuantity": 0,
            "profitLossAmount": 0,
            "referencePrice": 0,
            "countStatus": "string",
            "inOutStatus": "string",
            "remark": "string"
          }
        ]
      }, null, 2));
      
      if (error.response) {
        console.error('响应状态:', error.response.status);
        console.error('响应数据:', error.response.data);
        
        // 检查是否是.NET后端的空引用错误
        if (error.response.data && error.response.data.message && 
            error.response.data.message.includes('Object reference not set to an instance of an object')) {
          console.error('检测到.NET空引用错误');
          console.log('可能的原因:');
          console.log('1. 后端期望的字段名称不匹配');
          console.log('2. 后端模型中的必填字段缺失');
          console.log('3. 数据类型不匹配导致的转换问题');
          console.log('\n请将上方的请求数据复制到Swagger中测试！');
        }
      } else if (error.request) {
        console.error('请求发出但未收到响应');
      } else {
        console.error('请求配置错误:', error.message);
      }
      console.groupEnd();
      
      // 抛出错误以在外部catch中处理
      throw error;
    }
    
    if (response && response.success) {
      ElMessage.success(`保存成功，盘点单号：${response.data?.CountCode || response.data?.countCode || '未知'}`);
      router.push('/InventoryCount');
    } else {
      ElMessage.error(response?.message || '保存失败');
    }
  } catch (error) {
    console.error('保存失败详情:', error)
    console.error('错误类型:', error.name)
    console.error('错误信息:', error.message)
    if (error.response) {
      console.error('响应状态:', error.response.status)
      console.error('响应数据:', error.response.data)
    }
    ElMessage.error('保存失败：' + (error.message || '未知错误'))
  } finally {
    saveLoading.value = false
  }
}

// 重置表单
const handleReset = () => {
  ElMessageBox.confirm('确定要重置所有数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    formRef.value?.resetFields()
    countItems.length = 0 // 清空明细
    // 重置所有字段，确保与API要求一致
    formData.countCode = ""
    formData.countType = "存货盘点"
    formData.startTime = ""
    formData.endTime = ""
    formData.warehouseId = null
    formData.creatorId = 1
    formData.handlerId = null
    formData.department = ""
    formData.createTime = new Date().toISOString()
    formData.countStatus = ""
    formData.outStatus = ""
    formData.inStatus = ""
    formData.remark = ""
    ElMessage.success('重置成功')
  })
}

// 处理仓库设置
const handleWarehouseModel = () => {
  router.push('/WarehouseModel')
}

// 取消操作
const handleCancel = () => {
  ElMessageBox.confirm('确定要离开吗？未保存的数据将丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    router.push('/inventoryCount')
  })
}

// 页面初始化
onMounted(async () => { 
  try {
    await Promise.all([ 
      fetchUserList(),
      fetchDeptList(), // 恢复部门列表加载
      fetchWarehouseList() // 添加仓库列表加载
    ])
    console.log('页面初始化完成') 
  } catch (error) {
    console.error('页面初始化失败:', error)
    ElMessage.error('页面初始化失败，请刷新页面重试')
  }
})
// 获取仓库列表
const fetchWarehouseList = async () => {
  try {
    console.log('正在获取仓库列表...')
    const response = await proxy.http.get('/api/Outbound/GetWarehouses/GetWarehouses', {}, false)
    if (response && response.code === 200) {
      // 将API返回的仓库数据转换为前端需要的格式
      warehouseList.value = response.data.map(item => ({
        id: item.id,
        name: item.warehouseName
      }))
    } else {
      ElMessage.error(response?.message || '获取仓库列表失败')
      // 设置默认仓库列表，确保页面正常显示
      warehouseList.value = [
        { id: 1, name: '仓库一' },
        { id: 2, name: '仓库二' },
        { id: 3, name: '仓库三' },
        { id: 4, name: '仓库四' },
        { id: 5, name: '仓库五' },
        { id: 6, name: '仓库八' },
        { id: 7, name: '仓库十' }
      ]
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败，请检查网络连接')
    // 异常情况下设置默认仓库列表
    warehouseList.value = [
      { id: 1, name: '仓库一' },
      { id: 2, name: '仓库二' },
      { id: 3, name: '仓库三' },
      { id: 4, name: '仓库四' },
      { id: 5, name: '仓库五' },
      { id: 6, name: '仓库八' },
      { id: 7, name: '仓库十' }
    ]
  }
}
</script>

<style scoped>
/* 原有样式保持不变，新增盈亏样式 */
.purchase-order-add-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 0 10px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.form-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.purchase-form {
  margin-top: 20px;
}

.total-summary {
  margin-top: 20px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.summary-display {
  text-align: center;
  font-size: 16px;
  flex-wrap: wrap;
  display: flex;
  justify-content: center;
  gap: 15px;
}

.summary-item {
  color: #606266;
  font-weight: 500;
  white-space: nowrap;
}

/* 盈亏样式 */
.profit {
  color: #67c23a; /* 盘盈绿色 */
}
.loss {
  color: #f56c6c; /* 盘亏红色 */
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-dialog {
  max-height: 60vh;
  overflow-y: auto;
}

.search-section {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 表单样式 */
:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 6px;
}

:deep(.el-button--success) {
  background-color: #67c23a;
  border-color: #67c23a;
}

:deep(.el-button--success:hover) {
  background-color: #85ce61;
  border-color: #85ce61;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .summary-display {
    gap: 10px;
    font-size: 14px;
  }
}

@media (max-width: 768px) {
  .purchase-order-add-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>